package com.example.lxq.retrofit_rxjavatest;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作者： lxq on 2017/4/28 15:57
 * 邮箱： 842202389@qq.com
 * 用途：
 */

public class DownloadManager {

    private static DownloadManager INSTANCE = null;
    private OkHttpClient client;

    private DownloadManager() {
        client = new OkHttpClient();
    }

    public static DownloadManager getINSTANCE() {
        if (INSTANCE == null) {
            INSTANCE = new DownloadManager();
        }
        return INSTANCE;
    }

    public void download(String url, DownloadObserver observer) {
        DownloadInfo item = getDownloadInfo(url);

        Observable.just(url)
                .create(new DownloadSubscribe(getDownloadInfo(url),client))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(observer);
    }

    private DownloadInfo getDownloadInfo(String url) {
        DownloadInfo item = new DownloadInfo(url);
        item.setFileName(url.substring(url.lastIndexOf("/")));
        item.setTotal(getContentLength(url));
        return item;
    }

    private long getContentLength(String url) {
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();

            if (response != null && response.isSuccessful()) {
                long len = response.body().contentLength();
                response.close();
                return len == 0 ? DownloadInfo.TOTAL_ERROR : len;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DownloadInfo.TOTAL_ERROR;
    }

}
